import { FC, useEffect, useRef, useState } from "react";
import "./index.less";
import Header from "./components/Header";
import { BigScreenContext, CurrentKey } from "./context/BigScreenContext";
import { IframePostMessageApi } from "@/utils/postMessage/IframePostMessageApi";
import { notification } from "@supcon/supcon-5t-design";
import MainBody from "./components/MainBody";
import { GlobalDataProvider } from "./context/chat";
import AnomalyProvider from "./context/AnomalyProvider";
import BGContainer from "./components/BGContainer";
import { clearChatContext } from "@/utils/chat";
// import Footer from "./components/Footer";
import Nav from "./components/Nav";
import { fetchLogin, fetchUserInfo } from "@/services/supcon-chat-tool/api/app";
import store from "store2";

const default_nav_list = ["question"];

const BigScreen: FC = () => {
  const [clientWidth, setClientWidth] = useState(0);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const chatRef = useRef<any>(null);
  const postMessageApi = new IframePostMessageApi();

  const token = localStorage.getItem("token");
  const [showBody, setShowBody] = useState(false);

  // 右侧对话是否全屏
  const [chatFull, setChatFull] = useState(false);
  const [shouldKeepZIndex, setShouldKeepZIndex] = useState(false);
  const [chartFull, setChartFull] = useState(false);

  // 添加activeTab状态
  const [activeTab, setActiveTab] = useState("裂解炉");

  // 判断是刷新页面还是从其他页面跳转进来
  const [currentKey, setCurrentKey] = useState<CurrentKey>(() => {
    const savedTab = sessionStorage.getItem(
      "bigScreenCurrentTab"
    ) as CurrentKey;
    return savedTab || "question";
  });
  // 异常预警 json 数据
  const [anomalyJson, setAnomalyJson] = useState<any>({});
  // 操作参数 json 数据
  const [paramJson, setParamJson] = useState<any>({});

  const [currentDevice, setCurrentDevice] = useState<string>("");
  const [currentPathDevice, setCurrentPathDevice] = useState<string>("");

  // 操作路径 json 数据
  const [pathJson, setPathJson] = useState<any>({});

  // 场景缓存的 数组， 默认是 首页
  const [navList, setNavList] = useState<any>(default_nav_list);

  const initNavList = () => {
    setNavList(default_nav_list);
  };

  const reCalculateSize = function () {
    const { clientWidth } = document.documentElement;
    document.documentElement.style.overflow = "hidden";
    if (!clientWidth) return;
    setClientWidth(clientWidth);
    if (clientWidth >= 1920) {
      document.documentElement.style.fontSize = "20px"; // 1rem  = 100px
    } else {
      document.documentElement.style.fontSize =
        20 * (clientWidth / 1920) + "px";
    }
  };

  const handleAutoLogin = async () => {
    let info = {
      username: "admin",
      // ! 这边需要确认下
      pass64: "Supcon@1304$",
      agree: true,
    };
    const loginRes = await fetchLogin({
      ...info,
      remember: false,
    });
    if (loginRes.isSuccess) {
      localStorage.setItem("token", loginRes.content.token);
      localStorage.setItem("refreshToken", loginRes.content.refreshToken);
      localStorage.setItem("tokenHead", loginRes.content.tokenHead);
      localStorage.setItem("tokenHeader", loginRes.content.tokenHeader);
      localStorage.setItem("orgCode", loginRes.content.orgCode);
      const infoRes = await fetchUserInfo();
      if (infoRes.isSuccess && infoRes.content) {
        store.set("userInfo", infoRes.content);
        setShowBody(true);
        // window.location.reload();
      }
    } else {
      notification.error({
        message: loginRes.msg,
      });
    }
  };

  // 当currentKey变化时，保存到se
  useEffect(() => {
    if (currentKey) {
      if (!navList.includes(currentKey)) {
        setNavList([...navList, currentKey]);
      }
    }
    if (currentKey === "question") {
      // 清空其他 场景的参数: 由于需要nav切换，就不再清除之前的缓存了
      // setAnomalyJson({});
      // setParamJson({});
      // setPathJson({});
    }
    if (currentKey && iframeRef?.current?.contentWindow) {
      postMessageApi.sendViewBackMessage(
        iframeRef?.current?.contentWindow,
        true
      );
      if (currentKey === "main" || currentKey === "question") {
        postMessageApi.sendAllAlarmMessage(
          iframeRef?.current?.contentWindow,
          []
        );
      }
      sessionStorage.setItem("bigScreenCurrentTab", currentKey);
    }
  }, [currentKey]);

  useEffect(() => {
    if (!token) {
      handleAutoLogin();
    } else {
      setShowBody(true);
    }
  }, [token]);

  useEffect(() => {
    reCalculateSize();
    clearChatContext();
    window.addEventListener("resize", reCalculateSize);

    return () => {
      window.removeEventListener("resize", reCalculateSize);
    };
  }, []);

  return (
    <>
      <BigScreenContext.Provider
        value={{
          currentKey,
          setCurrentKey,
          clientWidth,
          iframeRef,
          postMessageApi,
          chatFull,
          setChatFull,
          chartFull,
          setChartFull,
          chatRef,
          pathJson,
          setPathJson,
          currentDevice,
          setCurrentDevice,
          currentPathDevice,
          setCurrentPathDevice,
          anomalyJson,
          setAnomalyJson,
          paramJson,
          setParamJson,
          navList,
          setNavList,
          initNavList,
          activeTab,
          setActiveTab,
          shouldKeepZIndex,
          setShouldKeepZIndex
        }}
      >
        <AnomalyProvider>
          <GlobalDataProvider>
            <BGContainer>
              <Header></Header>
              {showBody && <MainBody />}
              <Nav></Nav>
              {/* <Footer></Footer> */}
            </BGContainer>
          </GlobalDataProvider>
        </AnomalyProvider>
      </BigScreenContext.Provider>
    </>
  );
};

export default BigScreen;
